package com.soda.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.soda.bean.Role;
import com.soda.bean.User;
import com.soda.service.RoleService;
import com.soda.service.UserService;
import com.soda.service.impl.RoleServiceImpl;
import com.soda.service.impl.UserServiceImpl;
import com.soda.util.PageInfo;
import com.soda.util.SelectUserInfo;

public class UserServlet extends HttpServlet {

	UserService us = new UserServiceImpl();
	RoleService rs = new RoleServiceImpl();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String param = request.getParameter("param");// 获得参数，由参数判断执行方法
		if (param != null) {
			
			// 修改信息
			if ("edit".equals(param)) {
				edit(request, response);
			}
			// 修改密码
			if ("editPWD".equals(param)) {
				editPWD(request, response);
			}
			// 查询所有用户
			if ("showAll".equals(param)) {
				if (request.getParameter("aaa") != null) {
					request.getSession().removeAttribute("sui");
				}
				showAllUser(request, response);
			}
			// 通过id查询用户
			if ("showUserBuId".equals(param)) {
				getUserById(request, response);
			}
			// 通过管理员对用户信息进行修改，修改项增加
			if ("editByAdmin".equals(param)) {
				editByAdmin(request, response);
			}
			// 通过ajax修改用户状态
			if ("editstate".equals(param)) {
				editState(request, response);
			}

			if ("daleteById".equals(param)) {
				deleteUserById(request, response);
			}
			if ("addUser".equals(param)) {
				addUser(request, response);
			}
			if ("ajaxloginname".equals(param)) {
				ajaxloginname(request, response);
			}
			if("xiaohui".equals(param)){
				xiaohui(request,response);
			}
		}
	}

	private void xiaohui(HttpServletRequest request,HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		request.getSession().invalidate();
		response.sendRedirect(request.getContextPath()+"/houtai/login.jsp");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	
	/*
	 * 
	 * 修改信息，获取表单值，并进入数据库进行修改
	 */
	public void edit(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String useLoginName = request.getParameter("useLoginName");
		String useName = request.getParameter("useName");
		String useIdCard = request.getParameter("useIdCard");
		int useSex = Integer.parseInt(request.getParameter("useSex"));
		String usePhone = request.getParameter("usePhone");
		String useAddress = request.getParameter("useAddress");
		String useEmail = request.getParameter("useEmail");

		// System.out.println(useId+"\t"+useLoginName+"\t"+useName+"\t"+useIdCard+"\t"+useSex+"\t"+usePhone+"\t"+useAddress+"\t"+useEmail);

		User u = (User) request.getSession().getAttribute("user");
		// System.out.println(u.getUseId()+" "+u.getUseLoginName());

		u.setUseLoginName(useLoginName);
		u.setUseName(useName);
		u.setUseIdCard(useIdCard);
		u.setUseSex(useSex);
		u.setUsePhone(usePhone);
		u.setUseAddress(useAddress);
		u.setUseEmail(useEmail);

		// 调用service方法进行修改
		if (us.editUserInfo(u) > 0) {
			// request.getSession().setAttribute("user", u);
			out.print("<script>alert('修改成功！');window.location.href='"
					+ request.getContextPath()
					+ "/houtai/pages/personalManager/detail.jsp';</script>");

		} else {
			out.print("<script>alert('修改失败！请稍后重试！');window.location.href='"
					+ request.getContextPath()
					+ "/houtai/pages/personalManager/detail.jsp';</script>");

		}

	}

	/*
	 * 修改密码
	 */
	public void editPWD(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		// 获得输入旧密码和新密码，并把密码和用户id同时传入作为条件，进行密码修改
		String oldpwd = request.getParameter("oldpwd");
		String newpwd = request.getParameter("newpwd");
		User u = (User) request.getSession().getAttribute("user");
		// 首先判断旧密码输入是否正确，如不正确则进行提示，否则则进行修改！
		if (!oldpwd.equals(u.getUsePassWord())) {
			out.print("<script>alert('对不起！修改失败！请检查旧密码输入是否正确！');window.location.href='"
					+ request.getContextPath()
					+ "/houtai/pages/personalManager/updatePs.jsp';</script>");
			return;
		}
		if (us.editPassWord(u.getUseId(), newpwd) > 0) {
			request.getSession().invalidate();
			out.print("<script>alert('修改成功！请重新登录！');parent.location.href='"
					+ request.getContextPath() + "/houtai/login.jsp';</script>");
			return;
		} else {
			out.print("<script>alert('对不起！修改失败！请检查格式是否正确！');window.location.href='"
					+ request.getContextPath()
					+ "/houtai/pages/personalManager/updatePs.jsp';</script>");
			return;
		}

	}

	// 全查所有user用户
	public void showAllUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PageInfo pi = new PageInfo();
		SelectUserInfo sui = new SelectUserInfo();
		request.setCharacterEncoding("utf-8");
		String loginname = request.getParameter("loginname");
		String uname = request.getParameter("uname");
		String ustate = request.getParameter("ustate");

		if (loginname != null) {// 分页条件赋值
			sui.setLoginname(loginname.length() == 0 ? null : loginname);
			sui.setUname(uname.length() == 0 ? null : uname);
			sui.setUstate(ustate.length() == 0 ? null : (Integer
					.parseInt(ustate)));
			request.getSession().setAttribute("sui", sui);
		} else {
			sui = (SelectUserInfo) request.getSession().getAttribute("sui");
		}

		pi.setPer(5);// 分页信息赋值
		pi.setTotal(us.getUserCount(sui));
		String p = request.getParameter("page");
		if (p != null) {
			pi.setPage(Integer.parseInt(p));
		}

		List<User> users = us.getAllUser(sui, pi);
		request.setAttribute("users", users);
		request.setAttribute("pi", pi);

		request.getRequestDispatcher("/houtai/pages/user/list.jsp").forward(
				request, response);
	}

	public void getUserById(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		String s = request.getParameter("s");
		User userById = us.getUserById(id);

		// 如果user为空，则说明数据不在，应判断
		request.setAttribute("userById", userById);
		if ("show".equals(s)) {
			request.getRequestDispatcher("houtai/pages/user/detail.jsp")
					.forward(request, response);
		} else if ("edit".equals(s)) {
			List<Role> roles = rs.getAllRole();
			request.setAttribute("roles", roles);

			request.getRequestDispatcher("houtai/pages/user/edit.jsp").forward(
					request, response);
		}
	}

	/*
	 * 通过管理员对人员信息进行修改
	 */
	public void editByAdmin(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String useid = request.getParameter("useId");
		String useLoginName = request.getParameter("useLoginName");
		String usePassWord = request.getParameter("usePassWord");
		String useName = request.getParameter("useName");
		String useIdCard = request.getParameter("useIdCard");
		String useSex = request.getParameter("sex");
		String usePhone = request.getParameter("usePhone");
		String useAddress = request.getParameter("useAddress");
		String useEmail = request.getParameter("useEmail");
		String role = request.getParameter("role");
		String useState = request.getParameter("useState");

		// System.out.println(useid+"\n"+useLoginName+" "+usePassWord+" "+useName+" "+useIdCard+" "+sex+" "+usePhone+" "+useAddress+" "+useEmail+" "+role+" "+useState);

		User u = new User();
		u.setUseId(Integer.parseInt(useid));
		u.setUseLoginName(useLoginName);
		u.setUsePassWord(usePassWord);
		u.setUseName(useName);
		u.setUseIdCard(useIdCard);
		u.setUseSex(Integer.parseInt(useSex));
		u.setUsePhone(usePhone);
		u.setUseAddress(useAddress);
		u.setUseEmail(useEmail);
		u.getRole().setRolId(Integer.parseInt(role));
		u.setUseState(Integer.parseInt(useState));

		if (us.editUserInfoByAdmin(u) > 0) {
			// 修改成功
			showAllUser(request, response);
			// request.getRequestDispatcher("/houtai/pages/user/list.jsp").forward(request,
			// response);
		} else {
			// 修改失败
		}
	}

	public void editState(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		int uid = Integer.parseInt(request.getParameter("id"));
		int ustate = Integer.parseInt(request.getParameter("ustate")) == 1 ? 0
				: 1;

		// System.out.println(uid+" "+ustate);

		if (us.editUserState(uid, ustate) > 0) {
			// 成功

			out.print(ustate);
		}

	}

	private void deleteUserById(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int useId = Integer.parseInt(request.getParameter("id"));
		// System.out.println(useId);

		if (us.deleteById(useId) > 0) {
			showAllUser(request, response);
		}

	}

	public void addUser(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String useLoginName = request.getParameter("useLoginName");
		String usePassWord = request.getParameter("usePassWord");
		String useName = request.getParameter("useName");
		String useIdCard = request.getParameter("useIdCard");
		String useSex = request.getParameter("useSex");
		String usePhone = request.getParameter("usePhone");
		String useAddress = request.getParameter("useAddress");
		String useEmail = request.getParameter("useEmail");
		String role = request.getParameter("role");
		String useState = request.getParameter("useState");

		// System.out.println(useLoginName+" "+usePassWord+" "+useName+" "+useIdCard+" "+useSex+" "+usePhone+" "+useAddress+" "+useEmail+" "+role+" "+useState);

		User u = new User();
		u.setUseLoginName(useLoginName);
		u.setUsePassWord(usePassWord);
		u.setUseName(useName);
		u.setUseIdCard(useIdCard);
		u.setUseSex(Integer.parseInt(useSex));
		u.setUsePhone(usePhone);
		u.setUseAddress(useAddress);
		u.setUseEmail(useEmail);
		u.getRole().setRolId(Integer.parseInt(role));
		u.setUseState(Integer.parseInt(useState));

		if (us.addUser(u) > 0) {
			System.out.println("添加成功");
			showAllUser(request, response);
		}
	}

	/*
	 * ajax验证修改信息时登录名唯一性
	 */
	public void ajaxloginname(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String loginname = new String(request.getParameter("loginname")
				.getBytes("ISO-8859-1"), "utf-8");
		String ids = request.getParameter("id");
		if (ids != null) {
			
			int id = Integer.parseInt(ids);
			String uname = us.getNameById(id);

			if (uname.equals(loginname)) {
				return;
			} else {
				if (us.ajaxSelectLoginName(loginname) > 0) {
					// 查找到，用户名不可用
					out.print("对不起！该用户名已被占用！");

				} else {
					// 未找到,用户名可用
					out.print("√");

				}
			}

		}else{
			if (us.ajaxSelectLoginName(loginname) > 0) {
				// 查找到，用户名不可用
				out.print("对不起！该用户名已被占用！");

			} else {
				// 未找到,用户名可用
				out.print("√");

			}
		}

	}
}
